package com.tanhua.dubbo.api.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.Visitors;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

@DubboService(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        //判断该访客今日是否已经访问过
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").lte(maxDate), //同一个字段添加多个条件时需要使用andOperator()
                        Criteria.where("date").gte(minDate))
        );

        Visitors visitors = this.mongoTemplate.findOne(query, Visitors.class);
        if (null != visitors) {
            //更新用户信息（选择性）
            Query queryUpdate = Query.query(Criteria.where("userId").is(userId)
                    .and("visitorUserId").is(visitorUserId));
            Update update = Update.update("date", System.currentTimeMillis());
            UpdateResult updateResult = this.mongoTemplate.updateFirst(queryUpdate, update, Visitors.class);
            return Convert.toStr(updateResult.getMatchedCount());
        }

        //记录访客信息
        visitors = new Visitors();
        visitors.setId(ObjectId.get());
        visitors.setUserId(userId);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setDate(System.currentTimeMillis());
        visitors.setFrom(from);
        this.mongoTemplate.save(visitors);

        return visitors.getId().toString();
    }

    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Criteria criteria = Criteria.where("userId").is(userId);
        //查询该用户上一次查询列表的时间
        String hashKey = Convert.toStr(userId);
        Object lastDate = this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, hashKey);
        if(null != lastDate){
            criteria.and("date").gte(Convert.toLong(lastDate));
        }

        Query query = Query.query(criteria).with(pageRequest);
        return this.mongoTemplate.find(query, Visitors.class);
    }

    /**
     * 按照时间倒序排序，查询最近的访客信息
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Visitors> topVisitor(Long userId, Integer page, Integer pageSize) {
        PageInfo<Visitors> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //按来访时间排序
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);

        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        //记录查询访客表的时间
        String hashKey = Convert.toStr(userId);
        this.redisTemplate.opsForHash().put(VISITOR_REDIS_KEY, hashKey, Convert.toStr(System.currentTimeMillis()));
        pageInfo.setRecords(visitorsList);
        return pageInfo;
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }


}
